# -*- coding: utf-8 -*-
#coding=utf-8

import config
from action.admin.base import adminAction
from model.product import product
from model.category import category
from model.image import image
from model.album import album
from model.user import user
from model.company import company
'''
Admin controller: producing product administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '产品管理'):
        adminAction.__init__(self, name)

    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'add':
            return self.add()
        elif name == 'delete':
            return self.delete()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        elif name == 'edit':
            return self.edit()
        elif name == 'map':
            return self.map()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'update':
            return self.update()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        productObj = product()
        listData = productObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        productList = productObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/product/list', page, count, totalCount)
        self.privData['PRODUCT_LIST'] = productList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('productList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        productObj = product()
        listData = productObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        productList = productObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/product/list', page, count, totalCount)
        self.privData['PRODUCT_LIST'] = productList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('productBatchDel')
        
    def delete(self):
        inputParams = self.getInput()
        try:
            condition={'id': inputParams['id']}
            product().delete(condition)
        except Exception, e:
            return self.success(msg='产品删除失败: %s' % e, url=self.makeUrl('/admin/product/list'))

        return self.success(msg='产品删除成功', url=self.makeUrl('/admin/product/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            product().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/product/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/product/list'))

    def edit(self):
        inputParams = self.getInput()
        condition={'id': inputParams['id']}
        productObj = product().getOne('*', condition)
        if not productObj:
            return self.error(msg = '该产品不存在', url=self.makeUrl('/admin/product/list'))

        condition={}
        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        self.privData['PRODUCT'] = productObj
        self.privData['CURRENT_IMG'] = productObj["picture"]

        userList = user().getList('*', condition)
        self.privData['USER_LIST'] = {}
        for item in userList:
            self.privData['USER_LIST'][item['id']] = item['nickname']

        companyList = company().getList('*', condition)
        self.privData['COMPANY_LIST'] = {}
        for item in companyList:
            self.privData['COMPANY_LIST'][item['id']] = item['name']


        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_URL_LIST'] = {};
        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['SUBMIT_NAME'] = "picture"

        return self.display('productEdit')

    def update(self):
        inputParams= self.getInput()  
        data = {
            'name':          inputParams['name'],
            'price':         inputParams['price'],
            'discount':      inputParams['discount'],
            'desc':          self.htmlunquote(inputParams['desc']),
            'company':       inputParams['company'],
            'picture':       inputParams['picture'],
            'category':      inputParams['category'],
            'telephone':     inputParams['telephone'],
            'contact':       inputParams['contact'],
            'email':         inputParams['email'],
            'rank':          inputParams['rank'],
            'address':       inputParams['address'],
            'longitude':     inputParams['longitude'],
            'latitude':      inputParams['latitude'],
            'region':        inputParams['region'],
            'owner':         inputParams['owner'],
        }
        try:
            condition = {'id': inputParams['id']}
            product().update(data,condition)
        except Exception, e:
            return self.error(msg = '产品修改失败: %s' % e, url=self.makeUrl('/admin/product/list'))

        return self.success('产品修改成功', url=self.makeUrl('/admin/product/list'))

    def map(self):
        return self.display('map_select_widget')


    def add(self):
        condition = {}
        categoryList = category().getList('*', condition)

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        userList = user().getList('*', condition)
        self.privData['USER_LIST'] = {}
        for item in userList:
            self.privData['USER_LIST'][item['id']] = item['nickname']

        companyList = company().getList('*', condition)
        self.privData['COMPANY_LIST'] = {}
        for item in companyList:
            self.privData['COMPANY_LIST'][item['id']] = item['name']

        self.privData['IMG_URL_LIST'] = {};
        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "picture"

        return self.display('productAdd')


    def save(self):
        inputParams= self.getInput()
        data = {
            'name':          inputParams['name'],
            'price':         inputParams['price'],
            'discount':      inputParams['discount'],
            'desc':          self.htmlunquote(inputParams['desc']),
            'company':       inputParams['company'],
            'picture':       inputParams['picture'],
            'category':      inputParams['category'],
            'telephone':     inputParams['telephone'],
            'contact':       inputParams['contact'],
            'email':         inputParams['email'],
            'rank':          inputParams['rank'],
            'address':       inputParams['address'],
            'longitude':     inputParams['longitude'],
            'latitude':      inputParams['latitude'],
            'region':        inputParams['region'],
            'owner':         inputParams['owner'],
        }
        try:
            product().insert(data)
        except Exception, e:
            return self.error(msg = '新增产品失败: %s' % e, url=self.makeUrl('/admin/product/list'))

        return self.success('新增产品成功', url=self.makeUrl('/admin/product/list'))

